package com.example.grape_effect.effet.filter

import com.example.grape_effect.gl.common.ShaderConstant
import com.example.grape_effect.gl.common.ShaderParameter


class MagnifierFilter: LYFilter() {
    init {
        name = "magnifierFilter"

    }
    override var vertexShader = ShaderConstant.NO_FILTER_VERTEX_SHADER
    override var fragmentShader = """
        precision mediump float;
        varying vec2 textureCoordinate;
        //uniform samplerExternalOES vTexture;
        uniform sampler2D inputTexture;
        //放大镜的圆心
        uniform float pointCenter[2];
        //放大倍数
        uniform float opinionSize;
        // 放大镜的半径
        uniform float r;
        void main()
        {
            vec4 nColor=texture2D(inputTexture, textureCoordinate);
            //放大镜效果
            float dis=distance(vec2(textureCoordinate.x*2.0-1.0, (textureCoordinate.y*2.0 - 1.0)/0.5138), vec2(0.1, 0.3));

            //以r为中心进行放大，因为纹理是 旋转90°的，因此坐标x、y的方向改变了, textureCoordinate的xy变为yx，且正方向有变化
            //圆心
            vec2 o = vec2(pointCenter[0], pointCenter[1]);
            // 当前点到圆心的距离
            float d = distance(textureCoordinate, o);
            //                        //半径
            //                        float r = 0.25;
            //                        // 放大倍数
            //                        float opinionSize = 1.20;
            if (d<r)
            {
                nColor = texture2D(inputTexture, vec2(o.x + (textureCoordinate.x -o.x)/opinionSize, o.y + (textureCoordinate.y -o.y)/opinionSize));
            }
            gl_FragColor=nColor;
    }
    """.trimIndent()

    override fun addParameters() {
        super.addParameters()
        parameters["pointCenter"] = ShaderParameter("pointCenter",ShaderParameter.TYPE_UNIFORM, ShaderParameter.VALUE_TYPE_FLOAT_ARRAY)
        parameters["opinionSize"] = ShaderParameter("opinionSize",ShaderParameter.TYPE_UNIFORM, ShaderParameter.VALUE_TYPE_FLOAT)
        parameters["r"] = ShaderParameter("r",ShaderParameter.TYPE_UNIFORM, ShaderParameter.VALUE_TYPE_FLOAT)
    }

    /**
     * *  centerPoint 按照纹理来的,纹理是[0f,1f] 放大镜的圆心 是纹理映射的坐标
     * r 放大镜的半径 因为纹理映射范围是[0 , 1] 因此半径取值[0 , 0.5] ， 当取值1的时候，会整体放大，看不到放大镜
     * opinionSize 放大系数，<1时候是缩小镜， >1时候是 放大镜
     */
    fun setArgs(
        centerPoint: FloatArray,
        r: Float,
        opinionSize: Float
    ) {
        parameters["pointCenter"]?.value = centerPoint
        parameters["opinionSize"]?.value =opinionSize
        parameters["r"]?.value =r
    }

    override fun draw() {
        setArgs(floatArrayOf(0.5f,0.5f), 0.5f,1.4f)
        super.draw()
    }
}